<?php
namespace Base\Controller;

use Library\UploadFile;
use Think\Model;
use Think\Page;

/**
 * 增删改查基类
 * Class CurdAdminController
 * @package Base\Controller
 */
class CurdController extends BaseAdminController
{

    protected $table; //表名
    protected $model; //模型
    protected $relation;//关联
    protected $upload;//是否有上传字段
    protected $uploadConfig;//上传参数配置
    protected $urlConfig;//跳转配置参数

    public function __construct($relation = true, $upload = false, $uploadConfig = array(
        'input_name' => 'coverFile',//文本框name
        'save_path' => 'cover',//保存路径
        'data_field' => 'cover'//数据库字段
    ))
    {
        parent::__construct();
        $this->table = hump2underline(CONTROLLER_NAME);//获取当前控制器对应的表名
        $this->relation = $relation;
        $this->upload = $upload;
        $this->uploadConfig = $uploadConfig;
        $this->urlConfig = array(
            'add_success' => U('showList'),
            'add_error' => '',
            'edit_success' => U('showList'),
            'edit_error' => '',
            'del_success' => U('showList'),
            'del_error' => '',
        );
        $this->initModel();
    }

    /**
     * 初始化模型
     */
    private function initModel()
    {
        if ($this->relation) {
            $this->model = D($this->table)->relation($this->relation);
        } else {
            $this->model = M($this->table);
        }
    }

    /**
     * 删除
     * @param string $id 要删除的id，多个以,分割
     */
    public function del($id)
    {
        $arr = explode(',', $id);
        $i = 0;
        foreach ($arr as $k => $v) {
            if (!$v) {
                continue;
            }
            $this->model->where('id=' . $v)->setField('status', 0);
            $i++;
        }
        $this->success('删除' . $i . '条数据', $this->urlConfig['del_success']);
    }

    /**
     * 彻底删除
     * @param string $id 要删除的id，多个以,分割
     */
    public function deleted($id)
    {
        $arr = explode(',', $id);
        $i = 0;
        foreach ($arr as $k => $v) {
            if (!$v) {
                continue;
            }
            //删除图片
            $data = $this->model->find($id);
            if ($data['cover']) {
                //删除文件
                $upConfig = C('UPLOADS');
                removeFile($upConfig['PATH'] . '/' . $data['cover']);
            }
            //删除富文本文件
            if ($data['content']) {
                //删除文件
                removeContentFiles($data['content']);
            }
            $this->model->where('id=' . $v)->delete();
            $i++;
        }
        $this->success('彻底删除' . $i . '条数据', $this->urlConfig['del_success']);
    }

    /**
     * 恢复删除
     * @param string $id 要恢复的id，多个以,分割
     */
    public function recover($id){
        $arr = explode(',', $id);
        $i = 0;
        foreach ($arr as $k => $v) {
            if (!$v) {
                continue;
            }
            $this->model->where('id=' . $v)->setField('status', 1);
            $i++;
        }
        $this->success('恢复删除' . $i . '条数据', $this->urlConfig['del_success']);
    }
    /**
     * 新增
     */
    public function add()
    {
        $data = $this->model->create();
        if (!$data) {
            $this->error($this->model->getError());
        } else {
            if ($this->upload) {
                //上传图片
                $input_name = $this->uploadConfig['input_name'];
                $save_path = $this->uploadConfig['save_path'];
                $data_field = $this->uploadConfig['data_field'];
                if ($_FILES[$input_name]) {
                    $up = new UploadFile();
                    $info = $up->upFile($save_path, array('jpg', 'png', 'jpeg', 'gif'));
                    $data[$data_field] = $info[$input_name]['savepath'] . $info[$input_name]['savename'];
                }
                //上传视频
                if ($_FILES['videoFile']) {
                    $up = new UploadFile();
                    $info = $up->upFile('video', array('mp4', 'avi', 'wmv', 'rm', 'rmvb', '3gp'));
                    $data['video'] = $info['videoFile']['savepath'] . $info['videoFile']['savename'];
                }
            }

            $data = $this->addAfter($data);
            $add = $this->model->add($data);
            $this->addEnd($add);
        }
    }

    /**
     * @param $data
     * @return mixed
     * 新增数据处理
     */
    protected function addAfter($data)
    {
        return $data;
    }

    /**
     * @param $data
     * @return mixed
     * 编辑数据处理
     */
    protected function editAfter($data)
    {
        return $data;
    }

    /**
     * 编辑
     * */
    public function edit()
    {
        $data = $this->model->create();
        if (!$data) {
            $this->error($this->model->getError());
        } else {
            if (!$data) {
                $this->error($this->model->getError());
            } else {
                if ($this->upload) {
                    $input_name = $this->uploadConfig['input_name'];
                    $save_path = $this->uploadConfig['save_path'];
                    $data_field = $this->uploadConfig['data_field'];
                    //上传图片
                    if ($_FILES[$input_name]) {
                        $sel = $this->model->find($data['id']);
                        if ($sel[$data_field]) {
                            //删除
                            $upConfig = C('UPLOADS');
                            removeFile($upConfig['PATH'] . '/' . $sel[$data_field]);
                        }
                        $up = new UploadFile();
                        $info = $up->upFile($save_path, array('jpg', 'png', 'jpeg', 'gif'));
                        $data[$data_field] = $info[$input_name]['savepath'] . $info[$input_name]['savename'];
                    }
                    //上传视频
                    if ($_FILES['videoFile']) {
                        $video_info = $this->model->where(array('id'=>$data['id']))->getField('video');
                        if (!empty($video_info)) {
                            //删除原来视频文件
                            $upConfig = C('UPLOADS');
                            removeFile($upConfig['PATH'] . '/' . $video_info);
                        }
                        $up = new UploadFile();
                        $info = $up->upFile('video', array('mp4', 'avi', 'wmv', 'rm', 'rmvb', '3gp'));
                        $data['video'] = $info['videoFile']['savepath'] . $info['videoFile']['savename'];
                    }
                }
            }
            $data = $this->editAfter($data);
            $add = $this->model->save($data);
            if ($add) {
                $this->success('操作成功', $this->urlConfig['edit_success']);
            } else {
                $this->error('操作失败', $this->urlConfig['edit_error']);
            }
        }
    }

    /**
     * 展示列表
     * */
    public function showList()
    {
        $this->getAll();
        $this->show('');
    }

    /**
     * 编辑界面
     * @param $id
     */
    public function showEdit($id)
    {
        if (!$id) {
            $this->error('非法操作');
        }
        $select = $this->model->find($id);
        if (empty($select)) {
            $this->error('非法操作');
        }
        $this->assign('data', $select);
        $this->show('');
    }

    /**
     * 新增界面
     * */
    public function showAdd()
    {
        $this->show('');
    }

    /**
     * 获取所有数据并注入模板
     * */
    protected function getAll()
    {
        if(I('get.del')){
            $map['status'] = 0;
        }else{
            $map['status'] = 1;
        }
        $count = $this->model->where($map)->count();
        $page = new Page($count, 20);
        $show = $page->show();
        if ($this->relation) {
            $list = $this->model->relation($this->relation)->where($map)->order('id desc')->limit($page->firstRow . ',' . $page->listRows)->select();
        } else {
            $list = $this->model->where($map)->order('id desc')->limit($page->firstRow . ',' . $page->listRows)->select();
        }
        $this->assign('list', $list);
        $this->assign('page', $show);
    }

    /**
     * @param $id
     * @param int $reviewed 0拒绝 1通过
     * 审核
     */
    public function reviewed($id, $reviewed = 1)
    {
        $arr = explode(',', $id);
        $i = 0;
        foreach ($arr as $k => $v) {
            if (!$v) {
                continue;
            }
            $this->model->where('id=' . $v)->setField('reviewed', $reviewed);
            $i++;
        }
        $this->success(($reviewed ? '已审核' : '已驳回') . $i . '条数据', $this->urlConfig['del_success']);
    }

    /**
     * 获取指定配置参数
     * @param $key
     * @return mixed
     */
    protected function getConfig($key)
    {
        $map = array(
            'key' => $key,
        );
        $sel = $this->model->where($map)->find();
        return $sel['value'];
    }

    /**
     * 设置指定配置
     * @param $key
     * @param $value
     * @return bool
     */
    protected function setConfig($key, $value)
    {
        $old = $this->model->where(array(
            'key' => $key,
        ))->find();
        if (empty($old)) {
            $act = $this->model->add(array(
                'key' => $key,
                'value' => $value,
            ));
        } else {
            $map = array(
                'key' => $key,
            );
            $act = $this->model->where($map)->setField('value', $value);
        }
        if ($act) {
            return true;
        } else {
            return false;
        }
    }

    protected function addEnd($add)
    {
        if ($add) {
            $this->success('操作成功', $this->urlConfig['add_success']);
        } else {
            $this->error('操作失败', $this->urlConfig['add_error']);
        }
    }

    /**
     * @return string
     * 上传多张图片
     */
    public function upPhoto(){

        $upload = new \Think\Upload();// 实例化上传类
        $upload->exts      =     array('jpg', 'gif', 'png', 'jpeg');// 设置附件上传类型
        $upload->rootPath  =     './Public/Uploads/images/'; // 设置附件上传根目录
//        $upload->savePath  =     ''; // 设置附件上传（子）目录

        $upload->saveName = time().'_'.mt_rand();
//        $upload->saveName = array('date','Y-m-d');
        //上传文件
        $info = $upload->upload();
        // 上传单个文件
        if(!$info) {// 上传错误提示错误信息
            $this->error($upload->getError());
        }else{// 上传成功 获取上传文件信息
            $photo = $info['photo'];
            $photoPath = $photo["savepath"].$photo['savename'];
//
//            print_r('上传成功'.$photoPath);
//            foreach($info as $file){
//                echo $file['savepath'].$file['savename'];
//            }

            return $photoPath;
//            print_r("头像路径:".$photoPath);

//            print_r("上传成功");

            //头像处理
//            $path = $this->cropHead($photoPath,2);
            //修改头像资料
//            $id = $info['id'];

        }
    }

    /**
     * @return mixed
     * 上传多张图片
     */
    public function upMorePhoto() {
        if(IS_POST) {
            //设置文件保存目录
            $baseDir = './Public/Uploads/images/';
            $attachDir = date('Ym').'/';
//            $subDir = date('d');
//            $saveName = date('His').mt_rand();
            $saveName = $this->randno();

            //上传类配置信息
            $config = array(
                'maxSize' => 2097152,
                'exts' => array('jpg', 'jpeg', 'png', 'gif'),
                'rootPath' => $baseDir,
                'savePath' => $attachDir,
                'subName' => array('date', 'd'),
                'saveName' => $saveName,
                'hash' => false
            );
            //初始化上传类
            $upload = new \Think\Upload($config);
            //检查是否选择图片
            $inputName = 'photo';
            $total = 0;
            $data = array();
            foreach($_FILES[$inputName] as $key => $value) {
                foreach($value as $k => $v) {
                    $data[$k][$key] = $v;
                    if($key == 'name' && $v) {
                        $total++;
                    }
                }
            }
            if(!$total) {
                $this->error('请先选择要上传的图片！');
            }
            $uploadSuccess = $uploadFailure = 0;
            $result = array();
            //缩略图列表，数组为空则不生成缩略图
            //键为缩略图文件名后缀，例如：20140221abc_a.jpg
            //值为缩略图宽/高
//            $thumbList = array(
//                'a' => array(150, 150),
//                'c' => array(250, 250),
//                'm' => array(500, 500)
//            );
            //初始化缩略图类
//            if(!empty($thumbList)) {
//                $image = new \Think\Image();
//            }
            foreach($data as $key => $value) {
                if(!$value['name']) continue;
                //如果多图则从第二张开始设置新的文件名
                if($key >= 1) {
//                    $upload->saveName = date('His').mt_rand();
                    $upload->saveName = $this->randno();
                }
                //开始上传
                $file = $upload->upload(array($inputName => $value));
                //上传成功
                if(!empty($file)) {
                    $uploadSuccess++;

                    $path = $baseDir.$file[$inputName]['savepath'].$upload->saveName;
//                    $path = $file['savepath'].$file['savename'];
                    $photo = $file['photo'];
                    $photoPath = $photo["savepath"].$photo['savename'];

                    $photos[$key]=$photoPath;

//                    print_r($photoPath.'<br>');
//
//                    $goodsId = I('goodsId');
//                    print_r('商品id:'.$goodsId);

                    //缩略图
//                    if(!empty($thumbList)) {
//                        $path = $baseDir.$file[$inputName]['savepath'].$upload->saveName;
//                        $fileExt = $file[$inputName]['ext'];
//                        $filePath = $path.'.'.$fileExt;
//                        //生成缩略图，按照原图的比例
//                        foreach($thumbList as $thumbName => $thumbSize) {
//                            if(!$thumbName || empty($thumbSize)) continue;
//                            $image->open($filePath);
//                            $image->thumb($thumbSize[0], $thumbSize[1])->save($path.'_'.$thumbName.'.'.$fileExt);
//                        }
//                    }
                } else {
                    $uploadFailure++;
                }
                $result[] = array($upload->getError(), $file);
            }
            //成功提示
            if($uploadSuccess) {
//                $this->success($uploadSuccess.'张图片上传成功！');
            } else {
                $this->error('上传失败！');
            }
        } else {
            $value = array(
                'meta_title' => '上传照片'
            );
            $this->assign($value)->display();
        }
        return $photos;
    }

    public function randno() {
        list($usec, $sec) = explode(" ", microtime());
        $usec = substr(str_replace('0.', '', $usec), 0 ,4);
        $str  = rand(10,99);
        return date("His").$usec.$str;
    }
}